from django.shortcuts import render, get_object_or_404
from .models import Category, Food, Purchase

# Create your views here.

def index(request):
    total_foods = Food.objects.count()
    total_categories = Category.objects.count()
    recent_purchases = Purchase.objects.order_by('-purchase_date')[:5]
    
    context = {
        'total_foods': total_foods,
        'total_categories': total_categories,
        'recent_purchases': recent_purchases,
    }
    return render(request, 'food/index.html', context)

def category_list(request):
    categories = Category.objects.all()
    return render(request, 'food/category_list.html', {'categories': categories})

def food_list(request):
    foods = Food.objects.all().order_by('category', 'name')
    return render(request, 'food/food_list.html', {'foods': foods})

def food_detail(request, pk):
    food = get_object_or_404(Food, pk=pk)
    purchases = food.purchases.order_by('-purchase_date')
    return render(request, 'food/food_detail.html', {
        'food': food,
        'purchases': purchases
    })

def purchase_list(request):
    purchases = Purchase.objects.all().order_by('-purchase_date')
    return render(request, 'food/purchase_list.html', {'purchases': purchases})
